<template>
  <view class="consultation-page">
    <view class="header">
      <text class="title">向医生提问</text>
    </view>

    <!-- 医生信息展示 -->
    <view class="doctor-info" v-if="doctor">
      <view class="doctor-card">
        <text class="doctor-name">{{ doctor.name }}</text>
        <text class="doctor-title">{{ doctor.title }}</text>
        <text class="doctor-department">{{ doctor.department }}</text>
      </view>
    </view>

    <view class="form">
      <textarea v-model="description" placeholder="请详细描述您的病情"></textarea>

      <view class="options">
        <picker mode="selector" :range="consultationTypes" v-model="selectedConsultationType">
          <view class="picker">提问方式: {{ consultationTypes[selectedConsultationType] }}</view>
        </picker>
      </view>

      <view>
        <picker @change="onPatientChange" :value="selectedPatientIndex" :range="patients" range-key="name">
          <view class="picker">
            <text v-if="selectedPatient">问诊人: {{ selectedPatient.name }}</text>
            <text v-else>请选择患者</text>
          </view>
        </picker>
      </view>


      <button class="submit-btn" @click="submitConsultation">提交</button>
    </view>
    <view id="myDiv"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      doctorId: null,
      doctor: {}, // 存储医生信息
      description: '',
      consultationTypes: ['1对1提问'],
      selectedConsultationType: 0,
      patients: [], // 存储患者列表
      selectedPatient: null, // 当前选中的患者
      selectedPatientIndex: 0,// 选中的患者索引
      userId: null,
      feePrice: {},
      consultationType:'图文',
      consultationOrderRequest:{},
    };
  },

  onLoad(options) {

    if (options) {
      this.doctorId = options.id   //id存在

      this.fetchDoctorDetails(); // 加载医生信息
      this.fetchConsultations();
      this.fetchEvaluations();
      this.fetchPatients()

    }
  },

  methods: {


    async fetchPatients() {
      // 从本地存储中获取 userInfo
      const userInfo = uni.getStorageSync('userInfo');
      console.log(("userInfo:"+userInfo.id))
      // 检查 userInfo 是否存在
      if (!userInfo || !userInfo.id) {
        uni.showToast({
          title: '用户未登录，请先登录',
          icon: 'none',
          success: () => {
            // 跳转到登录页面
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        });
        return;
      }

     this.userId = userInfo.id; // 从 userInfo 中提取 id

      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/userinquiry/getUserInquiryOrderByUserId/${this.userId}`, // 反引号修正
        method: 'GET'
      });
      console.log(this.patients[0])
      if (!err && res.data.code === 200) {
        this.patients = res.data.data; // 存储患者数组
        if (this.patients.length > 0) {
          this.selectedPatient = this.patients[0]; // 默认选第一个
        }
      } else {
        console.error("获取患者失败:", err || res.data);
      }
    },
    onPatientChange(event) {
      this.selectedPatientIndex = event.detail.value;
      this.selectedPatient = this.patients[this.selectedPatientIndex];
    },
    async fetchDoctorDetails() {
      if (!this.doctorId) return;

      uni.showLoading({title: '加载中...'});

      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/doctor/getDoctorById?id=${this.doctorId}`,
        method: 'GET'
      });

      uni.hideLoading();

      if ( res.data.code === 200) {
        this.doctor = res.data.data;
      } else {
        uni.showToast({title: '获取医生信息失败', icon: 'none'});
      }
    },
    // 获取患者咨询列表
    async fetchConsultations() {
      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/doctor/getPatientConsultation?doctorId=${this.doctorId}`,
        method: 'GET'
      });


      if (res.data.code === 200) {
        // 假设 res.data.data 是一个对象，将其中的咨询数据提取出来
        this.consultations = res.data.data;
      } else {
        uni.showToast({title: '获取患者咨询失败', icon: 'none'});
      }
    },

// 获取医生评价列表
    async fetchEvaluations() {
      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/doctor/getDoctorEvaluation?doctorId=${this.doctorId}`,
        method: 'GET'
      });


      if (res.data.code === 200) {
        // 假设 res.data.data 是一个对象，将其中的评价数据提取出来
        this.evaluations = res.data.data;
      } else {
        uni.showToast({title: '获取医生评价失败', icon: 'none'});
      }
    },

    async fetchConsultationFee() {
      uni.showLoading({ title: '加载中...' });

      const [err, res] = await uni.request({

        url: `http://localhost:8080/app/userinquiry/getFeeByType/${this.consultationType}`,
        method: 'GET'
      });

      uni.hideLoading();

      if (err) {
        console.error('请求错误:', err);
        uni.showToast({ title: '获取费用失败', icon: 'none' });
        return;
      }

      console.log('支付费用数据:', res);
      console.log(res.data.data)
      if (res.data && res.data.code === 200) {
        this.feePrice = res.data.data.feePrice;  // 赋值给变量，前端页面显示
      } else {
        uni.showToast({ title: '获取费用失败', icon: 'none' });
      }
    },

    async submitConsultation() {
      if (!this.description || !this.selectedPatient) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      // 先查询支付金额
      await this.fetchConsultationFee();
      // 构造 ConsultationOrderRequest 对象
     this.consultationOrderRequest = {
        doctorId: this.doctorId,
        patientId: this.selectedPatient.id,
        description: this.description,
        consultationTypes: this.consultationTypes[this.selectedConsultationType],
        orderAmount: this.feePrice,
        userId: this.userId
      };

      // 显示支付弹窗
      uni.showModal({
        title: '支付确认',
        content: `本次问诊费用：¥${this.feePrice}`,
        confirmText: '去支付',
        success: async (res) => {
          if (res.confirm) {
            this.processAlipayPayment();
          }
        }
      });
    },

// 处理支付宝支付
    async processAlipayPayment(consultationOrderRequest) {
      uni.showLoading({ title: '创建订单...' });

      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/userinquiry/alipay`,
        method: 'POST',
        data: this.consultationOrderRequest


      });

      uni.hideLoading();

      if (err) {
        console.error('支付请求错误:', err);
        uni.showToast({ title: '失败', icon: 'none' });
        return;
      }
      console.log(res)
      if (res.data.code && res.statusCode === 200) {
        // 获取支付宝支付 URL，跳转到支付页面

        console.log(res.data.msg)
        document.write(res.data.msg)
        document.body.innerHTML = res.data.msg
      } else {
        uni.showToast({ title: '支付失败', icon: 'none' });
      }
    }
  }
};

</script>

<style lang="scss">
.doctor-info {
  padding: 20rpx;
  background-color: #f5f6fa;
}

.doctor-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.doctor-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.2;
}

.doctor-title {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.4;
  padding: 4rpx 16rpx;
  background: #e6f0ff;
  border-radius: 12rpx;
  align-self: flex-start;
}

.doctor-department {
  font-size: 26rpx;
  color: #888888;
  line-height: 1.4;
}

.consultation-page {
  padding: 20px;
}

.header {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.doctor-info {
  background: #f8f8f8;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}

.doctor-name {
  font-size: 18px;
  font-weight: bold;
}

.doctor-title,
.doctor-department {
  font-size: 14px;
  color: #666;
}

.form {
  display: flex;
  flex-direction: column;
}

textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #ccc;
  padding: 10px;
}

.picker, .patient-selection {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ccc;
}

.submit-btn {
  margin-top: 20px;
  background: #00c4b4;
  color: white;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  justify-content: center;
  line-height: 1;
}
</style>
